package main

import (
	"os"
	"os/exec"
	"regexp"
	"runtime"
)


func downloadResources(recipe *Recipe) (string, error) {
	// find wget
	var wget string
	if runtime.GOOS == "windows" {
		wget = "wget.exe"
	} else {
		wget = "/usr/bin/wget"
	}

	// download resources
	resources, err := findResources(recipe)
	if err != nil {
		return "", err
	}
	output := ""
	for _, resource := range resources {
		cmd := exec.Command(wget, "-p", "-k", "-P", home + "/.recp/", 
				resource)
		cmd.Stdin = os.Stdin
		//cmd.Stdout = os.Stdout
		//cmd.Stderr = os.Stderr
		//err := cmd.Run()
		o, err := cmd.CombinedOutput()
		output += string(o)
		if err != nil {
			return output, err
		}
	}

	return output, nil
}


func findResources(recipe *Recipe) ([]string, error) {
	rx, err := regexp.Compile(`(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?`)
	i := -1
	urls := []string{}
	for _, url := range rx.FindAllString(recipe.Description, i) {
		urls = append(urls, url)
	}
	if err != nil {
		return []string{}, err
	}
	if recipe.Image != "" {
		urls = append(urls, recipe.Image)
	}
	return urls, nil
}
